using System.Collections.Generic;
using UnityEngine;

public class CardManager : Singleton<CardManager>
{
    public GameObject CardContent;
    public string fileName = "Cards";
    private CardList cardList;

    private string cardPath = "Prefabs/CardPrefab";

    [SerializeField] private bool canAttack = false;
    private float cardAttackNum;
    private int maxHandSize = 10; // 最大手牌数量

    //private Dictionary<int, int> cardCountDict = new Dictionary<int, int>();  //存储每张卡已经使用的数量,作为弃牌区数字？

    //卡片数据
    public List<int> deck = new List<int>();
    public List<int> discardPile = new List<int>();
    public List<Card> handCards = new List<Card>();

    public Card draggedCard;

    // 弧形布局参数
    [Header("弧形布局设置")]
    public Vector2 rootPos = new Vector2(0, -300);          // 基准位置（屏幕底部中心）
    public float arcRadius = 500f;                          // 弧线半径
    public float arcAngle = 60f;                            // 总弧角度数
    public float cardSpacing = 10f;                         // 卡牌间距
    public float verticalOffset = 50f;                      // 垂直偏移量

    // 悬停效果
    [Header("悬停效果")]
    public float hoverHeight = 80f;                         // 悬停时抬升高度
    public float hoverScale = 1.2f;                         // 悬停时缩放
    public float animationSpeed = 8f;                       // 动画速度

    private Card hoveredCard;                               // 当前悬停的卡牌

    public bool CanAttack() => canAttack;


    private void Awake()
    {
        LoadCards();
    }

    private void Update()
    {
        if (CoreMechanismManager.Instance.currentState == State.AttackState && CoreMechanismManager.Instance.canGiveCardNum > 0)
        {
            canAttack = true;
        }
        else
        {
            canAttack = false;
        }

        UpdateCardLayout();
        HandleCardHover();
    }

    /// <summary>
    /// 构建初始卡组（游戏开始前调用）
    /// </summary>
    /// <param name="cardIds">卡牌ID列表（含重复ID）</param>
    public void BuildDeck(List<int> cardIds)
    {
        deck.Clear();
        discardPile.Clear();
        handCards.Clear();

        // 验证卡牌数量限制
        Dictionary<int, int> cardCount = new Dictionary<int, int>();
        foreach (int id in cardIds)
        {
            CardData card = GetCardDataById(id);
            if (card == null) continue;

            if (!cardCount.ContainsKey(id)) cardCount[id] = 0;

            // 检查是否超过最大数量
            if (cardCount[id] < card.maxCount)
            {
                deck.Add(id);
                cardCount[id]++;
            }
            else
            {
                Debug.Log($"卡牌 {card.name} 已达到最大数量 {card.maxCount}，跳过添加");
            }
        }

        ShuffleDeck();
    }

    /// <summary>
    /// 洗牌
    /// </summary>
    public void ShuffleDeck()
    {
        for (int i = deck.Count - 1; i > 0; i--)
        {
            int randomIndex = Random.Range(0, i + 1);
            (deck[i], deck[randomIndex]) = (deck[randomIndex], deck[i]);
        }
    }

    /// <summary>
    /// 从卡组抽卡
    /// </summary>
    /// <returns>抽到的卡牌数据</returns>
    public CardData DrawCard()
    {
        // 卡组为空时洗弃牌区
        if (deck.Count == 0)
        {
            if (discardPile.Count == 0)
            {
                Debug.Log("卡组和弃牌区均为空，无法抽卡！");
                return null;
            }

            deck.AddRange(discardPile);
            discardPile.Clear();
            ShuffleDeck();
        }

        int cardId = deck[deck.Count - 1];
        deck.RemoveAt(deck.Count - 1);
        return GetCardDataById(cardId);
    }

    /// <summary>
    /// 抽取指定数量的卡牌
    /// </summary>
    /// <param name="count">抽卡数量</param>
    public void DrawCards(int count)
    {
        if (draggedCard != null) draggedCard.ReSetOnDragCard();

        Debug.Log($"抽取 {count} 张卡牌");
        for (int i = 0; i < count; i++)
        {
            CardData cardData = DrawCard();
            if (cardData == null) break;

            CreateHandCard(cardData);
        }

        // 检查手牌溢出
        CheckHandOverflow();
    }

    /// <summary>
    /// 创建手牌
    /// </summary>
    /// <param name="cardData">卡牌数据</param>
    private void CreateHandCard(CardData cardData)
    {
        GameObject prefab = Resources.Load<GameObject>(cardPath);
        GameObject cardObj = Instantiate(prefab, CardContent.transform);
        Card card = cardObj.GetComponent<Card>();
        card.SetCardData(cardData);
        handCards.Add(card);
        UpdateCardLayout();
    }

    /// <summary>
    /// 将卡牌移至弃牌区
    /// </summary>
    /// <param name="card">要移除的卡牌</param>
    public void DiscardCard(Card card)
    {
        if (handCards.Contains(card))
        {
            handCards.Remove(card);
            discardPile.Add(card.id);
            Destroy(card.gameObject);
            UpdateCardLayout();
        }
    }

    /// <summary>
    /// 检查手牌是否溢出
    /// </summary>
    private void CheckHandOverflow()
    {
        while (handCards.Count > maxHandSize)
        {
            // 移除最早加入的手牌（索引0）
            Card cardToDiscard = handCards[0];
            Debug.Log($"手牌溢出！丢弃卡牌: {cardToDiscard.cardName}");
            DiscardCard(cardToDiscard);
        }
    }

    /// <summary>
    /// 通过ID获取卡牌数据
    /// </summary>
    public CardData GetCardDataById(int id)
    {
        if (cardList?.cards == null) return null;

        foreach (var card in cardList.cards)
        {
            if (card.id == id) return card;
        }
        return null;
    }

    /// <summary>
    /// 使用卡牌（从手牌移除并加入弃牌区）
    /// </summary>
    /// <param name="card">要使用的卡牌</param>
    public void UseCard(Card card)
    {
        if (handCards.Contains(card))
        {
            handCards.Remove(card);
            UpdateCardLayout();
        }
        discardPile.Add(card.id);
        Destroy(card.gameObject);
    }

    /// <summary>
    /// 清空所有卡牌
    /// </summary>
    public void ClearAllCards()
    {
        // 清空手牌
        foreach (var card in handCards) Destroy(card.gameObject);
        handCards.Clear();

        // 重置卡组和弃牌区
        deck.Clear();
        discardPile.Clear();
    }

    public void LoadCards()
    {
        TextAsset jsonFile = Resources.Load<TextAsset>(fileName);
        if (jsonFile != null)
        {
            cardList = JsonUtility.FromJson<CardList>(jsonFile.text);
            Debug.Log("Card data loaded successfully! Count: " + cardList.cards.Count);
        }
    }

    #region 手牌布局效果

    /// <summary>
    /// 更新卡牌布局（类似杀戮尖塔的弧形排列）
    /// </summary>
    public void UpdateCardLayout()
    {
        int cardCount = handCards.Count;
        if (cardCount == 0) return;

        // 计算总弧长和起始角度
        float totalArcLength = (cardCount - 1) * cardSpacing;
        float startAngle = -totalArcLength / 2f;

        for (int i = 0; i < cardCount; i++)
        {
            Card card = handCards[i];
            if (card == null) continue;

            // 计算当前卡牌在弧线上的位置
            float currentAngle = startAngle + i * cardSpacing;
            Vector2 targetPosition = CalculateArcPosition(currentAngle);
            float targetRotation = CalculateCardRotation(currentAngle);

            // 应用悬停效果
            if (card == hoveredCard)
            {
                targetPosition.y += hoverHeight;
            }

            // 平滑动画移动
            card.transform.localPosition = Vector2.Lerp(
                card.transform.localPosition,
                targetPosition,
                animationSpeed * Time.deltaTime
            );

            // 平滑旋转
            Quaternion targetRot = Quaternion.Euler(0, 0, targetRotation);
            card.transform.localRotation = Quaternion.Lerp(
                card.transform.localRotation,
                targetRot,
                animationSpeed * Time.deltaTime
            );

            // 设置层级（中间的卡牌在上层）
            card.transform.SetSiblingIndex(i);
        }
    }

    /// <summary>
    /// 计算卡牌在弧线上的位置
    /// </summary>
    private Vector2 CalculateArcPosition(float angle)
    {
        // 将角度转换为弧度
        float radian = angle * Mathf.Deg2Rad;

        // 计算在弧线上的位置
        float x = Mathf.Sin(radian) * arcRadius;
        float y = Mathf.Cos(radian) * arcRadius - arcRadius; // 减去半径使弧线底部在rootPos

        return new Vector2(x, y + verticalOffset) + rootPos;
    }

    /// <summary>
    /// 计算卡牌旋转角度（指向弧线圆心）
    /// </summary>
    private float CalculateCardRotation(float angle)
    {
        // 卡牌指向弧线圆心，所以旋转角度与位置角度相反
        return -angle * 0.3f; // 减少旋转幅度，使效果更自然
    }

    /// <summary>
    /// 处理卡牌悬停效果
    /// </summary>
    private void HandleCardHover()
    {
        // 检测鼠标位置
        Vector2 mousePosition = Input.mousePosition;
        RectTransform cardContentRect = CardContent.GetComponent<RectTransform>();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            cardContentRect, mousePosition, null, out Vector2 localMousePos);

        Card newHoveredCard = null;

        // 查找鼠标下的卡牌（从前往后检测）
        for (int i = handCards.Count - 1; i >= 0; i--)
        {
            Card card = handCards[i];
            if (card == null) continue;

            RectTransform cardRect = card.GetComponent<RectTransform>();
            Vector2 cardLocalPos = cardRect.anchoredPosition;

            // 简单的矩形碰撞检测
            if (IsPointInCard(localMousePos, cardLocalPos, cardRect.sizeDelta))
            {
                newHoveredCard = card;
                break;
            }
        }

        // 更新悬停状态
        if (newHoveredCard != hoveredCard)
        {
            // 恢复之前悬停的卡牌
            if (hoveredCard != null)
            {
                hoveredCard.transform.localScale = Vector3.one;
            }

            hoveredCard = newHoveredCard;

            // 应用新悬停卡牌的效果
            if (hoveredCard != null)
            {
                hoveredCard.transform.localScale = Vector3.one * hoverScale;
                hoveredCard.transform.SetAsLastSibling(); // 置顶显示
            }
        }
    }

    #endregion

    /// <summary>
    /// 检测点是否在卡牌范围内
    /// </summary>
    private bool IsPointInCard(Vector2 point, Vector2 cardPos, Vector2 cardSize)
    {
        Vector2 halfSize = cardSize * 0.5f;
        return point.x >= cardPos.x - halfSize.x &&
               point.x <= cardPos.x + halfSize.x &&
               point.y >= cardPos.y - halfSize.y &&
               point.y <= cardPos.y + halfSize.y;
    }

    /// <summary>
    /// 检查是否是当前应该打出去的顺序
    /// </summary>
    /// <param name="expectedOrder">当前卡片的顺序</param>
    /// <returns></returns>
    public bool CalculateCardCount(int expectedOrder)
    {
        if (GameManager.Instance.curState == GameState.FirstTurn)
            return true;

        bool isValid = (expectedOrder == cardAttackNum);
        if (isValid) cardAttackNum++;

        Debug.Log($"出牌顺序检查 - 期望: {expectedOrder}, 当前: {cardAttackNum - 1}, 结果: {isValid}");
        return isValid;
    }

    /// <summary>
    /// 清空攻击次数
    /// </summary>
    public void ResetAttackCount()
    {
        cardAttackNum = 1;
    }
}